/*
 * @Description: 根据roles数组拦截路由
 * @Author: liushuang
 * @Date: 2022-03-27 14:57:29
 * @LastEditTime: 2022-10-10 17:02:46
 */
// eslint-disable-next-line import/no-extraneous-dependencies
import path from 'path-browserify'
import { hasRole } from '@/router/hasRole'

/**
 * @desc: 前端导出路由
 * @param {*} routes
 * @param {*} baseUrl
 * @return {[]}
 */
export function filterRoutes(routes, baseUrl = '/') {
  return routes
    .filter((route) => {
      if (route.meta && route.meta.roles) return hasRole(route.meta.roles)
      return true
    })
    .map((route) => {
      if (route.path !== '*') {
        route.path = path.resolve(baseUrl, route.path)
      }
      route.fullPath = route.path
      if (route.children) {
        route.children = filterRoutes(route.children, route.fullPath)
      }
      return route
    })
}

/**
 * @desc: setNewRoutes\flatRoutes  将三级以上的路由全部转为二级路由，确保可以被keep-alive缓存
 * @param {*} routes
 * @return {*}
 */
export const flatRoutes = (routes) => {
  let res = []
  routes.forEach((item) => {
    if (item.children) {
      res = res.concat(flatRoutes(item.children))
    } else {
      res.push(item)
    }
  })
  return res
}
export const setNewRoutes = (routes) => routes.map((item) => {
  if (item.children) {
    return {
      ...item,
      children: flatRoutes(item.children)
    }
  }
  return item
})

/**
 * @desc: 处理转换后的路由 修改路由的redirect 某些路由会因为权限被删除 导致父路由的redirect会指向404
 * @param {*} routes
 */
export const setRoutesRedirect = (routes) => routes.map((item) => {
  if (item.children?.length > 0) {
    return {
      ...item,
      redirect: item.children[0].path
    }
  }
  return item
})

export default { filterRoutes }
